package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.bo.WxglMallManagementControllerBo.RegCaptcha;
import com.cskaoyan.bean.bo.WxglMallManagementControllerBo.RegisterUser;
import com.cskaoyan.bean.bo.wjjBO.WXAuthResetBO;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.marketBean.*;
import com.cskaoyan.bean.vo.AdminLgoutVo;
import com.cskaoyan.config.shiroConfig.MyUsernamePasswordToken;
import com.cskaoyan.config.smsService.SmsService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.ArrayList;
import java.util.Map;

/**
 * 登录模块
 *
 * @author 曾添乐啦
 * @since 2022/12/30 08:57
 */
//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

  /*  *
     * Shiro安全框架 → 视频课程 4个课时 → 认证（登录）
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */

    @Autowired
    WXAuthService wxAuthService;

    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String type = "user";
        // 写业务
//在这里执行登录。Subject.login
        //subject只能作为局部变量，不能作为全局变量
        Subject subject = SecurityUtils.getSubject();
        try {
            //subject.login() 最终会执行 realm.dagetAuthentication
            MyUsernamePasswordToken token = new MyUsernamePasswordToken(username, password, type);
            subject.login(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断是否成功
        boolean authenticated = subject.isAuthenticated();
        //可以获取session信息，也可以获取器sessionId
        Session session = subject.getSession();

        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();

        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
//        UserInfo userInfo = new UserInfo();
//        adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        adminInfo.setAvatar("https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64");

        adminInfo.setNickName(primaryPrincipal.getUsername());
        loginUserData.setAdminInfo(adminInfo);
//        loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        loginUserData.setToken((String) session.getId());

        return BaseRespVo.ok(loginUserData);
    }

    @PostMapping("logout")
    public AdminLgoutVo logout() {
        AdminLgoutVo adminLgoutVo = new AdminLgoutVo();
        adminLgoutVo.setErrmsg("成功");
        adminLgoutVo.setErrno(0);
        return adminLgoutVo;
    }


    @RequestMapping("info")
    public BaseRespVo info(String token) {

        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();


        //开发完shiro之后，再整合
        InfoData infoData = new InfoData();
        String username = principal.getUsername();
//        infoData.setName("user123");
        infoData.setName(username);

        //根据primaryPrincipal做查询
        String avatar = principal.getAvatar();
//        infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        infoData.setAvatar(avatar);

        //对小程序端的权限管理
        ArrayList<String> roles = new ArrayList<>();
        roles.add("超级管理员");
        infoData.setRoles(roles);
        ArrayList<String> perms = new ArrayList<>();
        perms.add("*");
        infoData.setPerms(perms);


        return BaseRespVo.ok(infoData);
    }

  /*  *//**
     * Shiro安全框架 → 视频课程 4个课时 → 认证（登录）
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     *//*
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
        String username = (String)map.get("username");
        String password = (String)map.get("password");

        // 写业务

        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
        adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        adminInfo.setNickName("admin123");
        loginUserData.setAdminInfo(adminInfo);
        loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        return BaseRespVo.ok(loginUserData);
    }



    @RequestMapping("info")
    public BaseRespVo info(String token) {


        //开发完shiro之后，再整合
        InfoData infoData = new InfoData();
        infoData.setName("admin123");

        //根据primaryPrincipal做查询
        infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        ArrayList<String> roles = new ArrayList<>();
        roles.add("超级管理员");
        infoData.setRoles(roles);
        ArrayList<String> perms = new ArrayList<>();
        perms.add("*");
        infoData.setPerms(perms);


        return BaseRespVo.ok(infoData);
    }*/


    /**
     * wjj
     * Request URL: http://182.92.235.201:8083/wx/auth/reset
     * Request Method: POST
     * 密码重置
     */
    @RequestMapping("reset")
    public BaseRespVo goodsReset(@RequestBody WXAuthResetBO authResetBO) {

        int code = wxAuthService.updateUserPasswordByMobile(authResetBO);
        BaseRespVo<Object> baseRespVo = new BaseRespVo<>();
        if (code == 200){
            baseRespVo.setErrmsg("成功");
            baseRespVo.setErrno(0);
            return baseRespVo;
        }else {
            baseRespVo.setErrmsg("失败");
            baseRespVo.setErrno(10000);
            return baseRespVo;
        }
    }
    /**
     * @Author xiaowu
     * @Description //TODO 发送验证码
     * @Date 16:20 2023/1/2
     * @Param [number]  {"mobile":"13476606183"}
     * @return
     **/
    @PostMapping("regCaptcha")
    public BaseRespVo authRegCaptcha(@RequestBody @Valid RegCaptcha regCaptcha, HttpServletRequest request){
        ServletContext context = request.getServletContext();
        @Pattern(regexp = "1[3-9]\\d{9}") String number = regCaptcha.getMobile();
        SmsService.getMessage(number, context);
        System.out.println(1);
        return BaseRespVo.success();

    }

    /**
     * @Author xiaowu
     * @Description // 注册
     * @Date 16:50 2023/1/2
     * @Param []  {"username":"user222","password":"user222","mobile":"13476606183","code":"333542","wxCode":"the code is a mock one"}
     * @return {"errno":705,"errmsg":"手机号已注册"} //{"errno":200,"errmsg":"注册成功"} //{"errno":400,"errmsg":"验证码错误"}
     **/

    @RequestMapping("register")
    public BaseRespVo authRegisterUser(@RequestBody RegisterUser registerUser,HttpServletRequest request){
        String templateParam = (String) request.getServletContext().getAttribute(registerUser.getMobile());
        BaseRespVo baseRespVo = new BaseRespVo();
        templateParam = templateParam.substring(9,15);
        if (!registerUser.getCode().equals(templateParam)){
            baseRespVo.setErrno(400);
            baseRespVo.setErrmsg("验证码错误");
            return baseRespVo;
        }
        int code = wxAuthService.authRegisterUser(registerUser);
        if (code == 10000){
            baseRespVo.setErrno(705);
            baseRespVo.setErrmsg("手机号已注册");
            return baseRespVo;
        }
        baseRespVo.setErrno(200);
        baseRespVo.setErrmsg("注册成功");
        return baseRespVo;
    }
}
